package com.xx.pmis.web.util;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.xx.pmis.model.Account;
import com.xx.pmis.model.Subject;
import com.xx.pmis.services.AccountService;
import com.xx.pmis.services.SubjectService;

public class AccountUtil extends PMISBaseUtil {
	private static final Log log = LogFactory.getLog(AccountUtil.class);

	AccountService accountService = getPMISServices().getAccountService();
	SubjectService subjectService = getPMISServices().getSubjectService();
	CalculateBalance calculateBalance = new CalculateBalance();

	// 求新增凭证的凭证号，也就是最大凭证号加1
	public String getMaxAccountCode() throws NumberFormatException {
		// 把String类型转换成Double类型
		double accountCode1 = 0.0;
		try {
			accountCode1 = Double.parseDouble(accountService.getMaxAccountCodeFromAccount());
		} catch (Exception e) {
			log.info("【财务管理/记账本】查询最大凭证编号异常！" + e.toString());
		}
		double accountCode2 = accountCode1 + 1;
		String accountCode3 = String.valueOf(accountCode2);
		String accountCode4 = accountCode3.substring(0, accountCode3.lastIndexOf("."));

		return accountCode4;

	}

	// 求最大凭证号
	public String getMaxAccountCodeOfSystem() throws NumberFormatException {
		// 把String类型转换成Double类型
		double accountCode1 = 0.0;
		try {
			accountCode1 = Double.parseDouble(accountService.getMaxAccountCodeFromAccount());
		} catch (Exception e) {
			log.info("【财务管理/记账本】查询最大凭证编号异常！" + e.toString());
		}
		String accountCode2 = String.valueOf(accountCode1);
		String accountCode3 = accountCode2.substring(0, accountCode2.lastIndexOf("."));

		return accountCode3;

	}

	// 求系统中最新的一次期末余额
	public String getBalanceOfLastOnce() throws NumberFormatException {
		String balance = "";
		try {
			balance = accountService.getAccountByAccountCode(getMaxAccountCodeOfSystem()).getBalance();
		} catch (Exception e) {
			log.info("【财务管理/记账本】根据记账本明细代码查询该记账明细异常！" + e.toString());
		}
		return balance;
	}

	// 分别求出本月和上月的支出和收入和 （1 当前月 2 上月）
	public Map<String, String> getMonthReductionAndIncrease() {
		Map<String, String> map = new HashMap<String, String>();
		double currentReduction = 0.00, currentIncrease = 0.00, lastReduction = 0.00, lastIncrease = 0.00;
		String currentDate = CurrentDate.currentDate();
		String currentMonth = currentDate.substring(5, 7);
		String currentYear = currentDate.substring(0, 4);
		int year = Integer.parseInt(currentYear);
		// 把字符型数据转换成整型数据
		int cm = Integer.parseInt(currentMonth);
		if (cm == 1) {// 1月的上个月是12月
			currentYear = String.valueOf(year - 1);
			currentMonth = String.valueOf(12);
		} else {
			cm = cm - 1;
			currentMonth = String.valueOf(cm);
		}
		// 当前月
		List<Account> all1 = new ArrayList<Account>();
		try {
			all1 = accountService.getAllAccountByCondition(" where year(accountDate)='" + currentDate.substring(0, 4)
					+ "' and month(accountDate)='" + currentDate.substring(5, 7) + "'");
		} catch (Exception e) {
			log.info("【财务管理/记账本】查询当前年月记账记录异常！" + e.toString());
		}
		Iterator<?> it1 = all1.iterator();
		while (it1.hasNext()) {
			Account account1 = (Account) it1.next();

			String reduction = replaceAllRMB(account1.getReduction());
			String increase = replaceAllRMB(account1.getIncrease());
			if (reduction.equals("") || reduction.equals(null)) {
				reduction = "0.00";
			}
			if (increase.equals("") || increase.equals(null)) {
				increase = "0.00";
			}
			// 计算当前月支出和
			currentReduction = currentReduction + Double.parseDouble(reduction);
			// 计算当前月收入和
			currentIncrease = currentIncrease + Double.parseDouble(increase);

		}
		map.put("currentReduction", if1ZeroTo2Zero(new DecimalFormat("####.##").format(currentReduction)));
		map.put("currentIncrease", if1ZeroTo2Zero(new DecimalFormat("####.##").format(currentIncrease)));

		// 上月
		List<Account> all2 = new ArrayList<Account>();
		try {
			all2 = accountService.getAllAccountByCondition(" where year(accountDate)='" + currentYear
					+ "' and month(accountDate)='" + currentMonth + "'");
		} catch (Exception e) {
			log.info("【财务管理/记账本】查询上月记账记录异常！" + e.toString());
		}
		Iterator<?> it2 = all2.iterator();
		while (it2.hasNext()) {
			Account account2 = (Account) it2.next();
			String reduction = replaceAllRMB(account2.getReduction());
			String increase = replaceAllRMB(account2.getIncrease());
			if (reduction.equals("") || reduction.equals(null)) {
				reduction = "0.00";
			}
			if (increase.equals("") || increase.equals(null)) {
				increase = "0.00";
			}
			// 计算上月支出和
			lastReduction = lastReduction + Double.parseDouble(reduction);
			// 计算上月收入和
			lastIncrease = lastIncrease + Double.parseDouble(increase);

		}
		map.put("lastReduction", if1ZeroTo2Zero(new DecimalFormat("####.##").format(lastReduction)));
		map.put("lastIncrease", if1ZeroTo2Zero(new DecimalFormat("####.##").format(lastIncrease)));

		return map;
	}

	// 分别求出本月和上月的支出和收入和 （1 当前月 2 上月）
	public Map<String, String> getMonthReductionAndIncreaseBySsID(String ssID) {
		Map<String, String> map = new HashMap<String, String>();
		double currentReduction = 0.00, currentIncrease = 0.00, lastReduction = 0.00, lastIncrease = 0.00;
		String currentDate = CurrentDate.currentDate();
		String currentMonth = currentDate.substring(5, 7);
		String currentYear = currentDate.substring(0, 4);
		int year = Integer.parseInt(currentYear);
		// 把字符型数据转换成整型数据
		int cm = Integer.parseInt(currentMonth);
		if (cm == 1) {// 1月的上个月是12月
			currentYear = String.valueOf(year - 1);
			currentMonth = String.valueOf(12);
		} else {
			cm = cm - 1;
			currentMonth = String.valueOf(cm);
		}
		// 当前月
		List<?> all1 = new ArrayList<Account>();
		try {
			all1 = accountService.getAllAccountByCondition(" where year(accountDate)='" + currentDate.substring(0, 4)
					+ "' and month(accountDate)='" + currentDate.substring(5, 7) + "' and subjectSon.ssID='" + ssID
					+ "'");
		} catch (Exception e) {
			log.info("【财务管理/记账本】根据二级科目ID查询当前年月记账记录异常！" + e.toString());
		}
		Iterator<?> it1 = all1.iterator();
		while (it1.hasNext()) {
			Account account1 = (Account) it1.next();

			String reduction = replaceAllRMB(account1.getReduction());
			String increase = replaceAllRMB(account1.getIncrease());
			if (reduction.equals("") || reduction.equals(null)) {
				reduction = "0.00";
			}
			if (increase.equals("") || increase.equals(null)) {
				increase = "0.00";
			}
			// 计算当前月支出和
			currentReduction = currentReduction + Double.parseDouble(reduction);
			// 计算当前月收入和
			currentIncrease = currentIncrease + Double.parseDouble(increase);

		}
		map.put("currentReduction", if1ZeroTo2Zero(new DecimalFormat("####.##").format(currentReduction)));
		map.put("currentIncrease", if1ZeroTo2Zero(new DecimalFormat("####.##").format(currentIncrease)));

		// 上月
		List<?> all2 = new ArrayList<Account>();
		try {
			all2 = accountService.getAllAccountByCondition(" where year(accountDate)='" + currentYear
					+ "' and month(accountDate)='" + currentMonth + "' and subjectSon.ssID='" + ssID + "'");
		} catch (Exception e) {
			log.info("【财务管理/记账本】根据二级科目ID查询上月记账记录异常！" + e.toString());
		}
		Iterator<?> it2 = all2.iterator();
		while (it2.hasNext()) {
			Account account2 = (Account) it2.next();
			String reduction = replaceAllRMB(account2.getReduction());
			String increase = replaceAllRMB(account2.getIncrease());
			if (reduction.equals("") || reduction.equals(null)) {
				reduction = "0.00";
			}
			if (increase.equals("") || increase.equals(null)) {
				increase = "0.00";
			}
			// 计算上月支出和
			lastReduction = lastReduction + Double.parseDouble(reduction);
			// 计算上月收入和
			lastIncrease = lastIncrease + Double.parseDouble(increase);

		}
		map.put("lastReduction", new DecimalFormat("####.##").format(lastReduction));
		map.put("lastIncrease", new DecimalFormat("####.##").format(lastIncrease));

		return map;
	}

	// 把收入支出中的"-"、"￥"剔除掉
	public static String replaceAllRMB(String arg) {
		if(!arg.equals("")) {
			arg = arg.replaceAll("￥", "").replace("-", "");
		}

		return arg;

	}

	// 最近十二个月的收入支出以及余额
	public List<Account> getReductionAndIncreaseOfTwelveMonths() {
		// 合计
		double reductionTotal = 0.00, increaseTotal = 0.00;
		String currentDate = CurrentDate.currentDate();
		String currentMonth = currentDate.substring(5, 7);
		String currentYear = currentDate.substring(0, 4);

		int year = Integer.parseInt(currentYear);
		int month = Integer.parseInt(currentMonth);
		String y, m;

		List<Account> accountList = new ArrayList<Account>();
		for (int i = 0; i < 12; i++) {
			double currentReduction = 0.00, currentIncrease = 0.00;
			Account account = new Account();
			if (i != 0) {
				month = month - 1;
			}
			if (month == 0) {
				month = 12;
				year = year - 1;
			}

			y = String.valueOf(year);
			m = String.valueOf(month);
			if (m.length() == 1) {
				m = 0 + m;

			}
			// 当前月
			List<Account> all1 = new ArrayList<Account>();
			try {
				all1 = accountService.getAllAccountByCondition(" where year(accountDate)='" + y
						+ "' and month(accountDate)='" + m + "'");
			} catch (Exception e) {
				log.info("【财务管理/记账本】查询当前年月记账记录异常！" + e.toString());
			}
			Iterator<?> it1 = all1.iterator();
			while (it1.hasNext()) {
				Account account1 = (Account) it1.next();

				String reduction = replaceAllRMB(account1.getReduction());
				String increase = replaceAllRMB(account1.getIncrease());
				if (reduction.equals("") || reduction.equals(null)) {
					reduction = "0.00";
				}
				if (increase.equals("") || increase.equals(null)) {
					increase = "0.00";
				}
				// 计算当前月支出和
				currentReduction = currentReduction + Double.parseDouble(reduction);
				// 计算当前月收入和
				currentIncrease = currentIncrease + Double.parseDouble(increase);

			}
			account.setIncrease(if1ZeroTo2Zero(new DecimalFormat("####.##").format(currentIncrease)));
			account.setReduction(if1ZeroTo2Zero(new DecimalFormat("####.##").format(currentReduction)));
			account.setBalance(if1ZeroTo2Zero(new DecimalFormat("####.##").format(currentIncrease - currentReduction)));
			account.setAccountDate(y + "-" + m);
			if ((currentIncrease - currentReduction) < 0) {
				account.setAccountDesc(y + m);
			} else {
				account.setAccountDesc(y + m);
			}
			accountList.add(account);

			reductionTotal = reductionTotal + currentReduction;
			increaseTotal = increaseTotal + currentIncrease;
		}

		// 合计
		Account account2 = new Account();
		account2.setAccountDate("合计");
		account2.setReduction(if1ZeroTo2Zero(new DecimalFormat("####.##").format(reductionTotal)));
		account2.setIncrease(if1ZeroTo2Zero(new DecimalFormat("####.##").format(increaseTotal)));
		account2.setBalance(if1ZeroTo2Zero(new DecimalFormat("####.##").format(increaseTotal - reductionTotal)));
		account2.setAccountDesc("近一年收支情况表");
		accountList.add(account2);

		return accountList;
	}

	// 穿透明细
	public List<Account> getAllAccountByMonth(String date) {
		// 合计
		String year = date.substring(0, 4);
		String month = date.substring(4, 6);

		double currentReduction = 0.00, currentIncrease = 0.00;

		List<Account> accountList = new ArrayList<Account>();

		// 当前月
		List<Account> accountListTemp = new ArrayList<Account>();
		try {
			accountListTemp = accountService.getAllAccountByCondition(" where year(accountDate)='" + year
					+ "' and month(accountDate)='" + month + "'");
		} catch (Exception e) {
			log.info("【财务管理/记账本】查询当前年月记账记录异常！" + e.toString());
		}
		Iterator<Account> accountIterator = accountListTemp.iterator();
		while (accountIterator.hasNext()) {
			Account accountTemp = (Account) accountIterator.next();

			String reduction = replaceAllRMB(accountTemp.getReduction());
			String increase = replaceAllRMB(accountTemp.getIncrease());
			if (reduction.equals("") || reduction.equals(null)) {
				reduction = "0.00";
			}
			if (increase.equals("") || increase.equals(null)) {
				increase = "0.00";
			}
			// 计算当前月支出和
			currentReduction = currentReduction + Double.parseDouble(reduction);
			// 计算当前月收入和
			currentIncrease = currentIncrease + Double.parseDouble(increase);

			accountList.add(accountTemp);
		}
		Account accountTotal = new Account();
		accountTotal.setAccountID("88888");
		accountTotal.setTransferAccount("合计");
		accountTotal.setReduction(if1ZeroTo2Zero(new DecimalFormat("####.##").format(currentReduction)) + "￥");
		accountTotal.setIncrease(if1ZeroTo2Zero(new DecimalFormat("####.##").format(currentIncrease)) + "￥");
		accountTotal
				.setBalance(if1ZeroTo2Zero(new DecimalFormat("####.##").format(currentIncrease - currentReduction)));
		accountList.add(accountTotal);

		return accountList;
	}

	// 结算
	public void payExpenseToAccount(String date, String subject, String num, String expense, String desc1, String desc2) {
		Account account = new Account();
		account.setAccountDate(date);
		Subject sub = null;
		try {
			sub = subjectService.getSubjectBySubjectID(subject);
		} catch (Exception e) {
			String errorPage = "根据【二级科目名称】查询该【二级科目】异常！" + e.toString();
			log.error(errorPage);
		}
		account.setSubjectID(subject);
		// 支出/旅游
		account.setTransferAccount("支出/" + sub.getSubName());
		// 支出金额 = (数量)*(票价)
		double red = (Double.parseDouble(num)) * (Double.parseDouble(expense));
		String reduction = String.valueOf(red);
		account.setReduction("-" + if1ZeroTo2Zero(reduction) + "￥");
		account.setIncrease("");
		double balance = calculateBalance.calculateAccountBalance();
		// 加收入，减支出，这里收入为"0"
		balance = balance + Double.parseDouble("-" + reduction);
		account.setBalance(if1ZeroTo2Zero(new DecimalFormat("####.##").format(balance)));
		account.setAccountDesc(desc1 + desc2);
		account.setPostDate(CurrentDate.currentDateAndTime());
		// 凭证编号
		account.setAccountCode(getMaxAccountCode());
		// 凭证ID
		account.setAccountID(getMaxAccountCode());
		try {
			accountService.saveOrUpdateAccount(account);
		} catch (Exception e) {
			String errorPage = "【旅游计划/交通费/结算】保存或更新【记账本】异常！" + e.toString();
			log.error(errorPage);
		}

	}

	/**
	 * 判断金额后面1个0还是2个0，如果1个0或者没有0，则补全到2个0，例如100.1，变成100.10
	 * 
	 * @param str
	 */
	public String if1ZeroTo2Zero(String str) {
		if (str.indexOf(".") != -1) {
			if (str.substring(str.lastIndexOf(".")).length() == 2) {// 1.0
				str = str + "0";
			} else if (str.substring(str.lastIndexOf(".")).length() > 3) {// 1.000,截取小数点后两位
				str = str.substring(0, str.lastIndexOf(".") + 3);
			} else if (str.substring(str.lastIndexOf(".")).length() < 2) {// 1.
				str = str + "00";
			} else {// ==3,1.00
			}
		} else {
			str = str + ".00";
		}
		return str;
	}
}
